<template>
	<div class="system-user-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search">
				<el-form :model="tableData.param" ref="queryRef" :inline="true" size="default">
					<el-form-item label="名称" prop="name">
						<el-input
							v-model="tableData.param.name"
							placeholder="请输入名称"
							clearable
							maxlength="20"
							@keyup.enter.native="dataList"
							style="width: 180px"
						/>
					</el-form-item>
					<el-form-item label="组件类型" prop="type">
						<el-select v-model="tableData.param.type" placeholder="请选择组件类型" clearable>
							<el-option v-for="item in typeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button size="default" type="primary" class="ml10" @click="dataList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button size="default" @click="resetQuery(queryRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
						<el-button size="default" type="success" class="ml10" @click="onOpenAdd" v-auth="'api/v1/iot/network/add'">
							<el-icon>
								<ele-FolderAdd />
							</el-icon>
							新增
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<el-space wrap v-if="tableData.data.length > 0" style="height: 100%; overflow-y: auto" alignment="flex-start" fill :fill-ratio="20">
				<el-card shadow="hover" v-for="(v, k) in tableData.data" :key="k" style="width: 200px" :body-style="{ padding: '0px 0px 10px 0px' }">
					<template #header>
						<el-row :gutter="20" align="middle" justify="start">
							<el-col :span="9">
								<el-tag style="width: 100px; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: clip">
									{{ v.typeName }}
								</el-tag>
							</el-col>
							<el-col :span="9">
								<div class="work-break" style="font-weight: bolder">{{ v.name }}</div>
							</el-col>
							<el-col :span="6">
								<el-switch
									v-model="v.state"
									class="ml-2"
									inline-prompt
									style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
									active-text="已启动"
									inactive-text="已停止"
									:active-value="1"
									:inactive-value="0"
									@change="editState(v.id, v.state)"
								/>
							</el-col>
						</el-row>
						<el-row :gutter="20" align="middle" justify="start">
							<el-col :span="9">
								<img :src="networkBg" width="90" height="90" />
							</el-col>
							<el-col :span="15">
								<el-row align="middle" justify="start">
									<div style="font-size: 12px; color: #9b9b9b; width: 180px" class="work-break-no-width">
										描述：
										<span v-if="v.description != ''">{{ v.description }}</span>
										<span v-else>无</span>
									</div>
								</el-row>
								<el-row align="middle" justify="start">
									<div style="font-size: 12px; color: #9b9b9b; width: 180px" class="work-break-no-width">详情：{{ v.host }}:{{ v.port }}</div>
								</el-row>
								<el-row align="middle" justify="start">
									<div style="font-size: 12px; color: #9b9b9b; width: 180px" class="work-break-no-width">注册时间：{{ v.createTimeStr }}</div>
								</el-row>
								<el-row align="middle" justify="start">
									<div style="font-size: 12px; color: #9b9b9b; width: 180px" class="work-break-no-width">所属部门：{{ v.deptName }}</div>
								</el-row>
							</el-col>
						</el-row>
					</template>
					<div class="common-layout">
						<el-container>
							<el-main style="padding: 5px 0px 5px 0px"> </el-main>
							<el-footer height="100%" style="text-align: center">
								<el-button-group>
									<el-button type="primary" :icon="View" @click="onOpenView(v.id)" v-auth="'api/v1/iot/network/get'">查看</el-button>
									<el-button type="primary" :icon="Edit" @click="onOpenEdit(v.id)" v-auth="'api/v1/iot/network/edit'">编辑</el-button>
									<el-button type="primary" :icon="Delete" @click="onRowDel(v.id)" v-auth="'api/v1/iot/network/delete'">删除</el-button>
								</el-button-group>
							</el-footer>
						</el-container>
					</div>
				</el-card>
			</el-space>
			<el-empty v-else description="暂无数据"></el-empty>
			<el-divider style="margin: 10px 0" />
			<pagination
				v-show="tableData.total > 0"
				:total="tableData.total"
				v-model:page="tableData.param.pageNum"
				v-model:limit="tableData.param.pageSize"
				@pagination="dataList"
			/>
		</el-card>
		<EditNetwork ref="editNetworkRef" @dataList="dataList" :type-data="typeOptions" :dept-tree="deptTree" />
		<ViewNetwork ref="viewNetworkRef" @dataList="dataList" :type-data="typeOptions" :dept-tree="deptTree" />
	</div>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue';
import EditNetwork from '/@/views/iot/network/component/editNetwork.vue';
import ViewNetwork from '/@/views/iot/network/component/viewNetwork.vue';
import { deleteNetWork, editNetWorkStates, getNetWorkList, getNetWorkTypeList } from '/@/api/iot/network';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { Delete, Edit, View } from '@element-plus/icons-vue';
import networkBg from '/@/assets/iot/network.webp';
import { getDeptSelectTree } from '/@/api/system/dept'; // 定义接口来定义对象的类型

// 定义接口来定义对象的类型
interface TableDataRow {
	name: string;
	typeName: string;
	host: string;
	port: number;
	state: number;
}

interface TableDataState {
	tableData: {
		data: Array<TableDataRow>;
		total: number;
		loading: boolean;
		param: {
			pageNum: number;
			pageSize: number;
			name: string;
			type: string;
			state: string;
		};
	};
	typeOptions: Array<object>;
	deptTree: any[];
}

export default defineComponent({
	name: 'networkList',
	components: { EditNetwork, ViewNetwork },
	setup() {
		const { proxy } = getCurrentInstance() as any;
		const editNetworkRef = ref();
		const viewNetworkRef = ref();
		const queryRef = ref();
		const dlRefs: any = ref([]);
		const state = reactive<TableDataState>({
			tableData: {
				data: [],
				total: 0,
				loading: false,
				param: {
					pageNum: 1,
					pageSize: 10,
					name: '',
					type: '',
					state: '',
				},
			},
			typeOptions: [],
			deptTree: [],
		});
		// 页面加载时
		onMounted(() => {
			dataList();
			initDeptSelectTree();
		});
		// 初始化表格数据
		const initDeptSelectTree = () => {
			getDeptSelectTree().then((res: any) => {
				state.deptTree = res.data.deptTree;
			});
		};
		// 获取数据列表
		const dataList = () => {
			getNetWorkList(state.tableData.param).then((res: any) => {
				let datas = res.data.list;
				// 获取网络类型
				getNetWorkTypeList().then((res1: any) => {
					let typeOptions = res1.data.list;
					for (let i = 0; i < datas.length; i++) {
						// 处理类型
						let type = datas[i].type;
						for (let j = 0; j < typeOptions.length; j++) {
							if (type === typeOptions[j].id) {
								datas[i].typeName = typeOptions[j].name;
								break;
							}
						}
						// 处理host port
						let configuration = JSON.parse(datas[i].configuration);
						datas[i].host = configuration.host;
						datas[i].port = configuration.port;
						// 处理时间
						datas[i].createTimeStr = proxy.moment.unix(datas[i].createTime).format('YYYY-MM-DD HH:mm:ss');
						// 处理部门数据
						flatten(state.deptTree).forEach((val: { deptId: number; deptName: string }) => {
							if (val.deptId === datas[i].deptId) {
								datas[i].deptName = val.deptName;
							}
						});
					}
					state.typeOptions = typeOptions;
					state.tableData.data = datas;
				});
				state.tableData.total = res.data.total;
			});
		};
		// 打开新增弹窗
		const onOpenAdd = () => {
			editNetworkRef.value.openDialog();
		};
		// 打开修改弹窗
		const onOpenEdit = (id: number) => {
			editNetworkRef.value.openDialog(id);
		};
		// 打开查看弹窗
		const onOpenView = (id: number) => {
			viewNetworkRef.value.openDialog(id);
		};
		// 删除
		const onRowDel = (id: number) => {
			let msg = '确定要删除所选数据吗';
			let ids: number[] = [];
			if (id) {
				ids.push(id);
			}
			if (ids.length === 0) {
				ElMessage.error('请选择要删除的数据');
				return;
			}
			ElMessageBox.confirm(msg, '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					deleteNetWork(ids).then(() => {
						ElMessage.success('删除成功');
						dataList();
					});
				})
				.catch(() => {});
		};
		// 格式化时间
		const formatter = (row: any, column: any, cellValue: any) => {
			return proxy.moment.unix(cellValue).format('YYYY-MM-DD HH:mm:ss');
		};
		// 重置按钮操作
		const resetQuery = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			formEl.resetFields();
			dataList();
		};
		// 改变状态
		const editState = (id: number, status: number) => {
			ElMessageBox.confirm('确定要启动/停止所选数据吗', '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					editNetWorkStates(id, status)
						.then(() => {
							ElMessage.success('启动/停止成功');
							dataList();
						})
						.catch(() => {
							state.tableData.data.forEach((data: any) => {
								if (data.id === id) {
									if (status == 0) {
										data.state = 1;
									} else {
										data.state = 0;
									}
								}
							});
						});
				})
				.catch(() => {
					state.tableData.data.forEach((data: any) => {
						if (data.id === id) {
							if (status == 0) {
								data.state = 1;
							} else {
								data.state = 0;
							}
						}
					});
				});
		};
		// 处理部门数据
		const flatten = (deptList: any): any[] => {
			let flatArray = [];
			for (let item of deptList) {
				flatArray.push(item);
				if (item.children && Array.isArray(item.children)) {
					flatArray = [...flatArray, ...flatten(item.children)];
				}
			}
			return flatArray;
		};
		return {
			flatten,
			initDeptSelectTree,
			networkBg,
			editState,
			onOpenView,
			viewNetworkRef,
			resetQuery,
			editNetworkRef,
			queryRef,
			dlRefs,
			dataList,
			onOpenAdd,
			onOpenEdit,
			onRowDel,
			formatter,
			Delete,
			Edit,
			View,
			...toRefs(state),
		};
	},
});
</script>
<style scoped lang="scss">
.system-user-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;

		.el-table {
			flex: 1;
		}
	}
}

.justify-between {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.work-break {
	width: 120px;
	word-break: keep-all;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.work-break-no-width {
	word-break: keep-all;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.el-card ::v-deep .el-card__header {
	background-image: linear-gradient(to right, rgba(217, 236, 255, 0), rgba(217, 236, 255, 0), rgba(217, 236, 255, 1));
}
</style>
